package com.business_clean.app.config

import android.graphics.Color
import android.view.Gravity
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.baidu.location.LocationClient
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.common.BaiduMapSDKException
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.business_clean.R
import com.business_clean.app.ext.getScreenHeight
import com.business_clean.app.ext.getScreenWidth
import com.business_clean.app.flutter.FlutterManager
import com.business_clean.app.network.NetHttpClient
import com.business_clean.app.service.ServerReporter
import com.business_clean.app.uitl.MMKVHelper
import com.business_clean.app.weight.loadCallBack.EmptyCallback
import com.business_clean.app.weight.loadCallBack.ErrorCallback
import com.business_clean.app.weight.loadCallBack.LoadingCallback
import com.business_clean.ui.activity.ErrorActivity
import com.business_clean.ui.activity.main.MainActivity
import com.effective.android.anchors.Project
import com.effective.android.anchors.Task
import com.effective.android.anchors.TaskCreator
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadSir
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.mmkv.MMKV
import me.hgj.mvvmhelper.base.Ktx
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.getColorExt
import me.hgj.mvvmhelper.widget.state.BaseEmptyCallback
import me.hgj.mvvmhelper.widget.state.BaseErrorCallback
import me.hgj.mvvmhelper.widget.state.BaseLoadingCallback
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.unit.Subunits
import rxhttp.RxHttpPlugins
import java.util.*

object TaskCreator : TaskCreator {
    override fun createTask(taskName: String): Task {
        return when (taskName) {
            InitNetWork.TASK_ID -> InitNetWork()
            InitComm.TASK_ID -> InitComm()
            InitUtils.TASK_ID -> InitUtils()
            InitBaidu.TASK_ID -> InitBaidu()
            else -> InitDefault()
        }
    }
}

class InitDefault : Task(TASK_ID, false) {
    companion object {
        const val TASK_ID = "0"
    }

    override fun run(name: String) {
        //统计上报的工具类
        ServerReporter.getInstance().initialize(Ktx.app)
        //头条的屏幕适配
        AutoSizeConfig.getInstance()
            .setExcludeFontScale(true)
            .unitsManager
            .setDesignSize(getScreenWidth().toFloat(), getScreenHeight().toFloat())
            .supportSubunits = Subunits.NONE

        //flutter 初始化
        FlutterManager.initEngine(Ktx.app)

        //防止项目崩溃，崩溃后打开错误界面
        CaocConfig.Builder.create()
            .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM
            .enabled(true) //是否启用CustomActivityOnCrash崩溃拦截机制 必须启用！不然集成这个库干啥？？？
            .showErrorDetails(true) //是否必须显示包含错误详细信息的按钮 default: true
            .showRestartButton(true) //是否必须显示“重新启动应用程序”按钮或“关闭应用程序”按钮default: true
            .logErrorOnRestart(false) //是否必须重新堆栈堆栈跟踪 default: true
            .trackActivities(true) //是否必须跟踪用户访问的活动及其生命周期调用 default: false
            .minTimeBetweenCrashesMs(2000) //应用程序崩溃之间必须经过的时间 default: 3000
            .restartActivity(MainActivity::class.java) // 重启的activity
            .errorActivity(ErrorActivity::class.java) //发生错误跳转的activity
            .apply()
    }
}


/**
 * 初始化网络
 */
class InitNetWork : Task(TASK_ID, false) {
    companion object {
        const val TASK_ID = "1"
    }

    override fun run(name: String) {
        //传入自己的OKHttpClient 并添加了自己的拦截器
        RxHttpPlugins.init(NetHttpClient.getDefaultOkHttpClient().build())
    }
}


//初始化常用控件类
class InitComm : Task(TASK_ID, false) {
    companion object {
        const val TASK_ID = "2"
    }

    override fun run(name: String) {
        SmartRefreshLayout.setDefaultRefreshInitializer { context, layout ->
            //设置 SmartRefreshLayout 通用配置
            layout.setEnableScrollContentWhenLoaded(true)//是否在加载完成时滚动列表显示新的内容
            layout.setFooterTriggerRate(0.6f)
        }
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
            //设置 Head
            ClassicsHeader(context).apply {
                setAccentColor(getColorExt(R.color.base_primary_text_title))
            }
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
            //设置 Footer
            ClassicsFooter(context).apply {
                setAccentColor(getColorExt(R.color.base_primary_text_title))
            }
        }
        //界面加载管理 初始化
        LoadSir.beginBuilder()
            .addCallback(LoadingCallback()) //加载
            .addCallback(ErrorCallback()) //错误
            .addCallback(EmptyCallback()) //空
            .setDefaultCallback(SuccessCallback::class.java) //设置默认加载状态页
            .commit()
    }
}

//初始化Utils
class InitUtils : Task(TASK_ID, false) {
    companion object {
        const val TASK_ID = "3"
    }

    override fun run(name: String) {
        //mmkv 存储
        MMKVHelper.initialize(appContext, Constant.INTERNAL_MMKV_PATH)
        Utils.init(appContext)
        //设置全局Toast 剧中提示
        //Toast设置统一样式
        //Kotlin中
        val defaultMaker = ToastUtils.getDefaultMaker()
        defaultMaker.setBgColor(Color.parseColor("#000000"))
        defaultMaker.setGravity(Gravity.CENTER, 0, 0)
        defaultMaker.setTextColor(Color.parseColor("#FFFFFF"))
    }
}

//百度地图
class InitBaidu : Task(TASK_ID, true) {
    companion object {
        const val TASK_ID = "4"
    }

    override fun run(name: String) {
        SDKInitializer.setAgreePrivacy(appContext, true)
        try {
            SDKInitializer.initialize(appContext)
        } catch (e: BaiduMapSDKException) {
            e.printStackTrace()
        }
        SDKInitializer.setCoordType(CoordType.BD09LL)
        LocationClient.setAgreePrivacy(true)
    }
}

class AppTaskFactory : Project.TaskFactory(TaskCreator)

/**
 * 模拟初始化SDK
 * @param millis Long
 */
fun doJob(millis: Long) {
    val nowTime = System.currentTimeMillis()
    while (System.currentTimeMillis() < nowTime + millis) {
        //程序阻塞指定时间
        val min = 10
        val max = 99
        val random = Random()
        val num = random.nextInt(max) % (max - min + 1) + min
    }
}